<?php
/***
 * Candy框架 Make接口
 * 
 * $Author: 刘森 (fingerboy@qq.com) $
 * $Date: 2022-3-5 17:20:22 $   
 */
  
declare(strict_types=1);
namespace Candy\Extend\Console\Command;

use Candy\Extend\Console\{Command,Input,Output};
use Candy\Extend\Console\Input\Argument;

abstract class Make extends Command
{
    protected $type;

    abstract protected function getStub();

    protected function configure(): void
    {
        $this->addArgument('name', Argument::REQUIRED, "The name of the class");
    }

    protected function execute(Input $input, Output $output)
    {
        $name = trim($input->getArgument('name'));
		
        $classname = $this->getClassName($name);
        $pathname = $this->getPathName($classname);
		
        if (is_file($pathname)) {
            $output->writeln('<error>' . $this->type . ':' . $classname . ' already exists!</error>');
            return false;
        }

        if (!is_dir(dirname($pathname))) {
            mkdir(dirname($pathname), 0755, true);
        }

        file_put_contents($pathname, $this->buildClass($classname));

        $output->writeln('<info>' . $this->type . ':' . $classname . ' created successfully.</info>');
    }

    protected function buildClass(string $name): string
    {
        $stub = $this->getStub();

        $namespace = trim(implode('\\', array_slice(explode('\\', $name), 0, -1)), '\\');

        $class = str_replace($namespace . '\\', '', $name);

        return str_replace(['{%className%}', '{%namespace%}', '{%app_namespace%}'], [
            $class,
            $namespace,
            $this->getNamespace($name),
        ], $stub);
    }

    protected function getPathName(string $name): string
    {
        return $this->getBasePath($name) . end(explode('\\', $name)) . '.class.php';
    }

    protected function getBasePath(string $name): string
    {
		return dirname
		(CANDYROOT . str_replace(['APP', '\\'], ['Application','/'], $name)) . '/';
    }

    protected function getClassName(string $name): string
    {
        if (strpos($name, '\\') !== false) {
            return $name;
        }

        if (strpos($name, '@')) {
            [$app, $name] = explode('@', $name);
        } else {
            $app = '';
        }

        if (strpos($name, '/') !== false) {
            $name = str_replace('/', '\\', $name);
        }
		
        return $this->getNamespace($app) . (empty($app) ? '' : '\\') . ucfirst(strtolower($name));
    }

    protected function getNamespace(string $app): string
    {
        return 'APP' . ($app ? '\\' . $app : '');
    }

}
